using System;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using GalleryItem = McePicasa.GalleryItem;
using Microsoft.MediaCenter;
using Microsoft.MediaCenter.UI;


namespace McePicasa
{
    /// <summary>
    /// This object contains the standard set of information displayed in the 
    /// search page UI.
    /// </summary>
    public class SettingPage : ContentPage
    {
        private long pageNumber;

        /// <summary>
        /// Construct a search page.
        /// </summary>
        public SettingPage()
        {
            // Create an object to track the search string and hook its 
            // submit event.
            searchValue = new EditableText(this);
            searchValue.Value = String.Empty;
            searchValue.Submitted += new EventHandler(OnSearchInputChanged);

            searchValueFlickr = new EditableText(this);
            searchValueFlickr.Value = String.Empty;
            searchValueFlickr.Submitted += new EventHandler(OnSearchInputChangedFlickr);

            //searchPageNumberFlickr = new EditableText(this);
            //searchPageNumberFlickr.Value = 1.ToString();
            //searchPageNumberFlickr.Submitted += new EventHandler(OnSearchInputChangedFlickr);

            this.pageNumber = 1;

            //this.pageNumberField = "Page: " + this.pageNumber.ToString();
            //FirePropertyChanged("PageNumberField");

            

            SetPrevNextUsage();

        }

        public void SetPrevNextUsage()
        {
            Command command = new Command(this, "",
              delegate(object sender, EventArgs e) {
                  if (this.pageNumber > 1)
                  {                      
                      //this.pageNumberField = this.pageNumber.ToString();
                      //OnSearchInputChangedFlickr(sender, e);
                      //FirePropertyChanged("PageNumberField");

                      ApplicationExperience experience = (ApplicationExperience)(filters[0] as BooleanChoice).Data["Experience"];
                      if (experience != null)
                      {
                          this.PageNumber--;
                          experience.SearchPhotoFlickr(this, searchValueFlickr.Value.ToLower(CultureInfo.CurrentCulture), pageNumber);
                      }
                  }
              });
            command.Data.Add("Type", "Prev");
            command.Data.Add("page", this);
            this.PrevCmd2 = command;                        

            Command command2 = new Command(this, "",
              delegate(object sender, EventArgs e) {                  
                  //this.pageNumberField = this.pageNumber.ToString();
                  //OnSearchInputChangedFlickr(sender, e);
                  //FirePropertyChanged("PageNumberField");

                  ApplicationExperience experience = (ApplicationExperience)(filters[0] as BooleanChoice).Data["Experience"];
                  if (experience != null)
                  {
                      this.PageNumber++;
                      experience.SearchPhotoFlickr(this, searchValueFlickr.Value.ToLower(CultureInfo.CurrentCulture), pageNumber);
                  }
              });
            command2.Data.Add("Type", "Next");
            command2.Data.Add("page", this);
            this.NextCmd2 = command2;
        }


        /// <summary>
        /// The current value to search with.
        /// </summary>
        public EditableText SearchValue
        {
            get
            {
                return searchValue;
            }
        }

        public EditableText SearchValueFlickr
        {
            get
            {
                return searchValueFlickr;
            }
        }



        /// <summary>
        /// A list of available filters on the content of this page.
        /// This list should only contain objects of type BooleanChoice.
        /// </summary>
        public IList Filters
        {
            get { return filters; }
        }

        public void SetFilters(IList value)
        {
            if (filters != value)
            {
                // Create a read only copy of the list.  This ensures
                // that we aren't surprised by someone else holding on
                // to the list and changing the contents.
                filters = ArrayList.ReadOnly(value);

                foreach (object o in filters)
                {
                    // Validate the contents of the list.
                    BooleanChoice filter = o as BooleanChoice;
                    if (filter == null)
                        throw new ArgumentException("Invalid contents for Filters list.  All contents must be of type BooleanChoice.");

                    // Hook the changed event.
                    filter.ChosenChanged += new EventHandler(OnSearchInputChanged);
                }

                FirePropertyChanged("Filters");
            }
        }

        /// <summary>
        /// Invoked when something that would affect our search has been modified.
        /// </summary>
        private void OnSearchInputChanged(object sender, EventArgs e)
        {
            // Clear out the search results.
            Content.Clear();

            // Get the current search string.
            string search = searchValue.Value.ToLower(CultureInfo.CurrentCulture);

            if (filters.Count > 0)
            {
                //Application.Current.MediaCenterEnvironment.Dialog("Searching...",
                //"McePicasa",
                //DialogButtons.Ok, 15, false);

                //bool FoundOne = false;
                this.StatusText = "Searching...";
                this.Data.Clear();
                this.Data.Add("found", false);
                this.Data.Add("processed", 0);
                int TotalNoOfAlbums = 0;

                foreach (BooleanChoice filter in filters)
                {
                    if (!filter.Value) continue;
                    User user = filter.Data["Experience"] as User;
                    if (user == null || user.PicasaUser == null)
                    {
                        Log.LogIt("No Experience stored on " + filter +
                            " or no active user");
                        continue;
                    }
                    TotalNoOfAlbums += user.PicasaUser.NoOfAlbums;
                }

                this.Data.Add("noofalbums", TotalNoOfAlbums);

                foreach (BooleanChoice filter in filters)
                {
                    // If the filter has been disabled, don't search it.
                    if (!filter.Value)
                        continue;

                    // Get the experience off of the item.
                    ApplicationExperience experience = filter.Data["Experience"] as ApplicationExperience;
                    if (experience == null || (experience as User).PicasaUser == null)
                    {
                        Log.LogIt("No Experience stored on " + filter +
                            " or no active user");
                        continue;
                    }


                    /* Search photo only
                    // Search that experience.                    
                    IList<GalleryItem> results = experience.SearchAlbum(this, search);
                    if (results != null) foreach (GalleryItem result in results)
                        {
                            // Add the search result to the content list.
                            Content.Add(result);
                            if (!FoundOne) FoundOne = true;
                        }
                    */

                    // Search that experience.
                    //IList<GalleryItem> photoResults = 
                    experience.SearchPhoto(this, search);
                    /*
                    if (photoResults != null) foreach (GalleryItem result in photoResults)
                        {
                            // Add the search result to the content list.
                            Content.Add(result);
                            if (!FoundOne) FoundOne = true;
                        }
                    //this.StatusText = "Done";
                    */
                }

                /*
                if (!FoundOne)
                {
                    GalleryItem gallItem = new GalleryItem(this, null as PicasaAlbum);
                    gallItem.Image = null;
                    gallItem.Description = "Nothing found!";
                    gallItem.Metadata = "Try a shorter text...";
                    Content.Add(gallItem);
                }
                */
            }
        }




        private void OnSearchInputChangedFlickr(object sender, EventArgs e)
        {
            // Clear out the search results.
            Content.Clear();

            PageNumber = 1;
            string search = searchValueFlickr.Value.ToLower(CultureInfo.CurrentCulture);
            //string pageNumber = searchPageNumberFlickr.Value.ToLower(CultureInfo.CurrentCulture);
            ApplicationExperience experience = (ApplicationExperience)(filters[0] as BooleanChoice).Data["Experience"];
            experience.SearchPhotoFlickr(this, search, this.pageNumber);

            #region For User Album only
            /*
            if (filters.Count > 0)
            {
                //Application.Current.MediaCenterEnvironment.Dialog("Searching...",
                //"McePicasa",
                //DialogButtons.Ok, 15, false);

                //bool FoundOne = false;
                this.StatusText = "Searching flickr...";
                this.Data.Clear();
                this.Data.Add("found", false);
                this.Data.Add("processed", 0);
                int TotalNoOfAlbums = 0;

                foreach (BooleanChoice filter in filters)
                {
                    if (!filter.Value) continue;
                    User user = filter.Data["Experience"] as User;
                    if (user == null || user.PicasaUser == null)
                    {
                        Log.LogIt("No Experience stored on " + filter +
                            " or no active user");
                        continue;
                    }
                    TotalNoOfAlbums += user.PicasaUser.NoOfAlbums;
                }

                this.Data.Add("noofalbums", TotalNoOfAlbums);

                ApplicationExperience experience = null;

                foreach (BooleanChoice filter in filters)
                {
                    // If the filter has been disabled, don't search it.
                    if (!filter.Value)
                        continue;

                    // Get the experience off of the item.
                    experience =  filter.Data["Experience"] as ApplicationExperience;
                    if (experience == null || (experience as User).PicasaUser == null)
                    {
                        Log.LogIt("No Experience stored on " + filter +
                            " or no active user");
                        continue;
                    }                    

                }                                
            }
            */
            #endregion
        }





        public void GoUp()
        {
            Application.Current.GoToMenu();
        }

        public string StatusText
        {
            get { return statusText; }
            set
            {
                if (statusText != value)
                {
                    statusText = value;
                    FirePropertyChanged("StatusText");
                }
            }
        }
        private string statusText = "";

        private EditableText searchValue;
        private EditableText searchValueFlickr;
        //private EditableText searchPageNumberFlickr;
        //private string pageNumberField;

        public long PageNumber
        {
            get { return pageNumber; }
            set { pageNumber = value; FirePropertyChanged("PageNumberField"); }
        }

        public string PageNumberField
        {
            get { return " Page " + pageNumber.ToString() + " "; }
            //set { pageNumberField = value;}
        }

        private Command nextCmd;
        private Command prevCmd;

        /*
        public EditableText SearchPageNumberFlickr
        {
            get { return searchPageNumberFlickr; }
            set { searchPageNumberFlickr = value; }
        }
         * */

        private IList filters;


        public Command NextCmd2
        {
            get { return nextCmd; }
            set { nextCmd = value; FirePropertyChanged("nextCmd"); }
        }


        public Command PrevCmd2
        {
            get { return prevCmd; }
            set { prevCmd = value; FirePropertyChanged("prevCmd"); }
        }

    }
}
